package com.zlm.tools.advice;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zlm
 * @date 2023/9/27
 */
@Slf4j
@Aspect
@Component
public class LogAdvice {

    @Pointcut("@annotation(com.zlm.tools.advice.Log)")
    private void logPointCut() {
    }

    @Around("logPointCut()")
    public Object logPrint(ProceedingJoinPoint joinPoint)throws  Throwable{

        System.out.println("======切面======");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (requestAttributes == null) {
            return joinPoint.proceed();
        }
        request = requestAttributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip  = request.getRemoteAddr();
        String method = request.getMethod();
        //获取请求参数
        Object[] args = joinPoint.getArgs();
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        log.info("请求url:{},方法类型:{},类名:{},方法名:{},参数:{}",url,method,className,methodName, JSONUtil.toJsonStr(args));


        return joinPoint.proceed();
    }

}
